/**
 * 
 */
const menuDao = require("../dao/menuDao");
const roleMenuDao = require("../dao/roleMenuDao");

module.exports = {
    // 查询所有菜单
    findAll: async () => {
        let menuList = await processArray("-1");
        return menuList;
    },
    // 添加一级菜单
    // addFirstLevel: async (params) => { 
    //     await menuDao.add
    // },
    // 添加菜单
    add: async (params) => {
        return await menuDao.add(params)
    },
    // 修改菜单
    update: async (params) => {
        return await menuDao.update(params)
    },
    // 删除菜单
    del: async (params) => {
        return await menuDao.del(params)
    },
    // 根据角色id查找菜单
    findAllByRoleId: async (params) => {
        // console.log('service:', params)
        // return await menuDao.findAllByRoleId(params)
        let menus = await roleMenuDao.findMenuByRoleId(params);
        // console.log("menus:", menus)
        return menus;
    },
    updateMenuByRoleId: async (params) => {
        let { roleId, menuIds } = params;
        // let oldMenuIds = await db.query("select * from role_menu where role_id = ?", [roleId]);
        // let oldMenuIds = await roleMenuDao.findMenuByRoleId({ roleId: roleId });
        // for (var i = 0; i < oldMenuIds.length; i++) {
        //     let oldMenuId = oldMenuIds[i]
        //     // await db.query("delete from role_menu where role_id = ?", [roleId])
        //     await roleMenuDao.delMenuByRoleId({ roleId: roleId })
        // }

        await roleMenuDao.delMenuByRoleId({ role_id: roleId })

        for (var i = 0; i < menuIds.length; i++) {
            let menuId = menuIds[i];
            roleMenuDao.create({ role_id: roleId, menu_id: menuId })
            // await db.query("INSERT INTO role_menu (role_id, menu_id) values(?,?) on duplicate key update role_id = role_id ", [roleId, menuId])
        }
    }
}

async function processArray(parent_id) {
    // let menuAry = await db.query("select * from menu where parent_id = ?", [parent_id])
    let params = { parent_id }
    let menuAry = await menuDao.findAllByParentId(params)
    if (menuAry.length > 0) {
        for (var i = 0; i < menuAry.length; i++) {
            let item = menuAry[i];
            let res = await processArray(item.id);
            item.children = res.length === 0 ? null : res;
        }
    }
    return menuAry;
}